class Vector2 {
  x: number;
  y: number;

  constructor(x: number = 0, y: number = 0) {
    this.x = x;
    this.y = y;
  }

  getLength() {
    return Math.sqrt(this.x ** 2 + this.y ** 2);
  }

  distanceTo(vector: Vector2) {
    return Math.sqrt((vector.x - this.x) ** 2 + (vector.y - this.y) * 2);
  }

  multiply(num: number) {
    this.x *= num;
    this.y *= num;
    return this;
  }

  add(vector: Vector2) {
    this.x += vector.x;
    this.y += vector.y;
    return this;
  }

  subtract(vector: Vector2) {
    this.x -= vector.x;
    this.y -= vector.y;
  }

  /**
   * 变为法向量 (-y, x);
   * @returns Vector2
   */
  normal() {
    const oldX = this.x;
    this.x = -this.y;
    this.y = oldX;
    return this;
  }

  unit() {
    const length = this.getLength();
    this.x /= length;
    this.y /= length;
    return this;
  }

  dot(vector: Vector2) {
    return this.x * vector.x + this.y * vector.y;
  }

  cross(vector: Vector2) {
    return this.x * vector.y - vector.x * this.y;
  }

  clone() {
    return new Vector2(this.x, this.y);
  }
}

export default Vector2;
